package ws;

import java.text.SimpleDateFormat;
import java.util.List;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

import model.*;
import entities.*;

import org.hibernate.*;
import org.hibernate.criterion.Restrictions;

import com.sun.research.ws.wadl.Request;

@Path("file")
public class TaiLieuRestful extends AbstractModel<Tailieucongty> {

	//http://localhost:8080/ProjectThuViecWSServer/rest/file/searchJson?tentl=&keyword=dat&madm=&mota=h&date1=&date2=
	
	@GET
	@Path("searchJson")
	@Produces(MediaType.APPLICATION_JSON)
	public List<Tailieucongty> search(@QueryParam("tentl") String tentl,
			@QueryParam("keyword") String keyword,
			@QueryParam("madm") String madm, @QueryParam("mota") String mota,
			@QueryParam("date1") String date1, @QueryParam("date2") String date2) {

		
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		DanhMucModel dmm = new DanhMucModel();
		
		
		try {
			tx = session.beginTransaction();
			Criteria cr = session.createCriteria(Tailieucongty.class);
			if (!tentl.equals("")) {
				cr.add(Restrictions.like("tentl", "%" + tentl + "%"));
			}
			if (!keyword.equals("")) {
				cr.add(Restrictions.eq("keyword", keyword));
			}
			if (!madm.equals("")) {
				cr.add(Restrictions.eq("danhmuc",
						dmm.find(Integer.parseInt(madm))));
			}
			if (!mota.equals("")) {
				cr.add(Restrictions.like("mota","%"+mota+"%"));
			}
			if ((!date1.equals("")) && (!date2.equals(""))) {
				SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
				cr.add(Restrictions.between("ngayupload", sdf.parse(date1),
						sdf.parse(date2)));
			}

			List<Tailieucongty> dstl = cr.list();
			tx.commit();
			return dstl;

		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
			return null;
		} finally {
			session.close();
		}
	}
	
	@GET
	@Path("test123456")
	@Produces(MediaType.TEXT_PLAIN)
	public String test(@QueryParam("a")String a){
		a="sdf";
		return a;
	}

	@GET
	@Path("findalljson")
	@Produces(MediaType.APPLICATION_JSON)
	public List<Tailieucongty> findAlljson() {
		TaiLieuModel tlm = new TaiLieuModel();
		return tlm.findAll();
	}
}
